#include "mainwindow.h"
#include "ui_mainwindow.h"

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(QString("解析"));//设置窗口的名称
    QMessageBox msg;
    msg.setText("lmp_log格式:\ntx_lmp0(rx_lmp0):<lmp pdu>(每1byte中间有空格）\n比如：rx_lmp0:06 33");
    msg.exec();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_openFileButton_clicked()
{
    QMessageBox msg;
    QString in_file_name;
    in_file_name = QFileDialog::getOpenFileName(
                       this, tr("open image file"),
                       "./", tr("Image files(*.txt)"));
    QFile in_file(in_file_name);
    if(!in_file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        msg.setText("打开读取文件失败!");
        msg.exec();
        return;
    }
    QTextStream in(&in_file);

    QString out_file_name = QDir::currentPath() + QDir::separator() + QString("lmp_parsing_out.txt");
    out_file_name = QDir::fromNativeSeparators(out_file_name);
    QFile out_file(out_file_name);
    if(!out_file.open(QIODevice::WriteOnly | QIODevice::Text)){
        msg.setText("打开写入文件失败!");
        msg.exec();
        return;
    }

    lmpanalysis lmpanalysis_show;
    string pkg_type;
    string pud;
    string pos_dir;
    while(!in.atEnd()){
        QString line_qstr = in.readLine();
        string line_str = line_qstr.toStdString();
        unsigned long long idx = line_str.find("tx_lmp0")  &
                                 line_str.find("rx_lmp0")  &
                                 line_str.find("tx_elmp0") &
                                 line_str.find("rx_elmp0") ;
        if(idx != string::npos){
            unsigned long long dat_idx = line_str.find(':',idx);
            string lmp_dat;
            if(dat_idx != string::npos){
                dat_idx += 1;
                string lmp_dat(line_str,dat_idx,line_str.size() - dat_idx);
                lmpanalysis_show.getlmpmsg(lmp_dat,pkg_type,pud,pos_dir);
                QByteArray lmp_dat_array(lmp_dat.c_str(), lmp_dat.length());
                out_file.write("lmp_dat:"+lmp_dat_array+"\n");
                QByteArray pos_dir_array(pos_dir.c_str(), pos_dir.length());
                out_file.write("dat_dir:"+pos_dir_array+"\n");
                QByteArray pkg_type_array(pkg_type.c_str(), pkg_type.length());
                out_file.write("pkg_type:"+pkg_type_array+"\n");
                QByteArray pud_array(pud.c_str(), pud.length());
                out_file.write("lmp_pdu:"+pud_array+"\n");
                out_file.write("---------------------------------\r\n");
            }
        }
    }
    in_file.close();
    out_file.close();
    msg.setText("写入文件成功!\n保存在:"+out_file_name);
    msg.exec();
}
